#include "GetAudioSignalInThread.h"

GetAudioSignalInThread::GetAudioSignalInThread(QObject *parent) : QThread(parent){ //TODO Refactor name with extract
    this->audioSignalGot = false;
    this->waveForm = NULL;
}

GetAudioSignalInThread::~GetAudioSignalInThread(){
    delete this->waveForm;
}

bool GetAudioSignalInThread::hasAudioSignalGot(){
    return this->audioSignalGot;
}

void GetAudioSignalInThread::_setVideoFileName(QString videoFileName){
    this->videoFileName = videoFileName;
}

void GetAudioSignalInThread::run(){
    this->audioSignalGot = false;
    if(!this->videoFileName.isEmpty() && !this->videoFileName.isNull()){
        Mlt::Profile profile("square_ntsc_wide");
        Mlt::Producer producer(profile, this->videoFileName.toUtf8().constData());
        int width = 200;
        int height = 200; //the higher those 2 data the higher the precision of the waveform
        Mlt::Frame *frame;
        this->nFrames = producer.get_length();
        this->fps = producer.get_fps();
        delete this->waveForm;
        *this->waveFormToFillOut = NULL;
        this->waveForm = new float[this->nFrames];
        for(int i=0; i<this->nFrames; i++){
            if(!this->dontTerminate){
                return;
            }
            frame = producer.get_frame(i);
            unsigned char* waves = frame->get_waveform(width, height);
            float mean = 0;
            for(int j=0; j<width*height; j++){
                    mean += int(waves[j]);
            }
            mean /= width*height;
            this->waveForm[i] = mean;
        }
        this->audioSignalGot = true;
    }
    *this->waveFormToFillOut = this->waveForm;
    emit dataExtracted();
}


void GetAudioSignalInThread::extractInformationsIntoTab(QString videoFileName, float **waveFormToFillOut){
    this->_setVideoFileName(videoFileName);
    this->waveFormToFillOut = waveFormToFillOut;
    this->dontTerminate = true;
    this->start();
    //TODO if it's already running I should just notify it in the run function with a variable taht we wan't to stop and start again
    this->setPriority(QThread::HighPriority);
}

int GetAudioSignalInThread::getNFrames(){
    return this->nFrames;
}

int GetAudioSignalInThread::getFps(){
    return this->fps;
}

void GetAudioSignalInThread::stopAndFreeMemory(){
    //TODO find out what to do to open quickly two several videos
    this->dontTerminate = false;
    this->wait();
    delete this->waveForm;
    this->audioSignalGot = false;
    this->waveForm = NULL;
    *this->waveFormToFillOut = NULL;
}
